
const db = require('../../../db/index')
const bcrypt = require("bcryptjs");

const addAsync = (req, res) => {
    let { username, password, nickname, email } = req.body.data
    if (!username || !password) return res.send({ status: 500, message: '用户名或密码不能为空' })
    if (!nickname) nickname = ''
    if (!email) email = ''
    password = bcrypt.hashSync(password, 10);
    const sql = `insert into t_user(username,password,nickname,email) values(?,?,?,?)`
    db.query(sql, [username, password, nickname, email], (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '添加失败' })
        res.send({ status: 200, message: '添加成功' })
    })
}


// 分页查询加模糊查询
const getAsync = (req, res) => {
    const data = req.body.data;
    var { password, username, pageSize, pageIndex } = data;
    if (!password) {
        password = ''
    }
    if (!username) {
        username = ''
    }
    let sql = `SELECT * FROM t_user where username like '%${username}%'  LIMIT ${(pageIndex - 1) * 10},${pageSize}`;

    db.query(sql, [username, password, pageSize, pageIndex], (err, result) => {
        if (err) {
            console.error(err);
            return handleDatabaseError(res, err);
        }

        if (result.length === 0) {
            return res.send({ status: 404, message: '未找到数据', data: [] });
            // return res.status(404).send({ status: 404, message: '未找到数据' });
        }

        res.status(200).send({ status: 200, message: '查询成功', data: result });
    });
};

// 错误处理函数
const handleDatabaseError = (res, err) => {
    console.error('数据库查询出错:', err);
    res.status(500).send({ status: 500, message: '服务器错误' });
};


const modifyAsync = (req, res) => {
    const sql = `update t_user set ? where id=?`
    const data = req.body
    db.query(sql, [data.data, data.id], (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '修改失败' })
        res.send({ status: 200, message: '修改成功' })
    })
}

const deleteAsync = (req, res) => {
    const sql = 'delete from t_user where id=?'
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '删除失败' })
        res.send({ status: 200, message: '删除成功' })
    })
}

module.exports = {
    addAsync: addAsync,
    getAsync: getAsync,
    deleteAsync: deleteAsync,
    modifyAsync: modifyAsync
}